/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package users;

import avenue.MyWindowEvent;
import avenue.Session;
import avenue.messageBox;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.AppUser;
import model.DBManager;

/**
 *
 * @author Aggelos
 */
public class ListUsersForm extends javax.swing.JFrame {
//Αλλαγή στο query1 και στο customize code γιατι το ερώτημα επέστρεφε μόνο όσους ειχαν ιδιο station id μετο πρώτο
    /**
     * Creates new form ListUsersForm
     */
    public ListUsersForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
        
        //Δικαιώματα  χρήστη
        jButton1.setEnabled(Session.canUserCreate(Session.USERS_MODULE));
        jButton3.setEnabled(Session.canUserUpdate(Session.USERS_MODULE));
        jButton2.setEnabled(Session.canUserDelete(Session.USERS_MODULE));
        usersTable.setVisible(Session.canUserRetrive(Session.USERS_MODULE));
        
        //Αλλαγή χρώματος 24/2/2013
        getContentPane().setBackground(Color.white);
          
      
        
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
     
      
       
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        usersquery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select u from AppUser u");
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(usersquery.getResultList());
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        usersTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση χρησών");
        setBackground(new java.awt.Color(255, 255, 255));
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/user_edit.png"))); // NOI18N
        jButton3.setText("Επεξεργασία");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 270, -1, -1));

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/user_delete.png"))); // NOI18N
        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 270, -1, -1));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/user_add.png"))); // NOI18N
        jButton1.setText("Νέος");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 270, -1, -1));

        usersTable.setGridColor(new java.awt.Color(255, 0, 0));
        usersTable.setNextFocusableComponent(jButton4);
        usersTable.setRowMargin(2);
        usersTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, usersTable, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${FName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${LName}"));
        columnBinding.setColumnName("Επίθετο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Διεύθυνση");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${city}"));
        columnBinding.setColumnName("Πόλη");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${zipCode}"));
        columnBinding.setColumnName("ΤΚ");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
        columnBinding.setColumnName("Τηλ");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
        columnBinding.setColumnName("Email");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${adt}"));
        columnBinding.setColumnName("ΑΤ");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${afm}"));
        columnBinding.setColumnName("ΑΦΜ");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${userName}"));
        columnBinding.setColumnName("User Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
        columnBinding.setColumnName("Password");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleId.roleName}"));
        columnBinding.setColumnName("Ρόλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationId.description}"));
        columnBinding.setColumnName("Σταθμός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        usersTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                usersTableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(usersTable);
        usersTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        usersTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        usersTable.getColumnModel().getColumn(2).setPreferredWidth(200);
        usersTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        usersTable.getColumnModel().getColumn(4).setPreferredWidth(75);
        usersTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        usersTable.getColumnModel().getColumn(7).setPreferredWidth(100);
        usersTable.getColumnModel().getColumn(8).setPreferredWidth(100);
        usersTable.getColumnModel().getColumn(9).setPreferredWidth(150);
        usersTable.getColumnModel().getColumn(10).setPreferredWidth(200);
        usersTable.getColumnModel().getColumn(11).setPreferredWidth(200);
        usersTable.getColumnModel().getColumn(12).setPreferredWidth(200);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 967, 164));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Διαχείριση Xρηστών");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(132, 55, 170, -1));

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton4.setText("Ακυρο");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(860, 350, 120, -1));

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButton5.setText("Αποθήκευση");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(860, 320, 120, -1));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imagesCAL4A9SX.jpg"))); // NOI18N
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 101, 53));

        jLabel5.setFont(new java.awt.Font("Snap ITC", 1, 24)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(0, 3, 130));
        jLabel5.setText("TelePass 1.0");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(117, 11, -1, 38));

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       
      
        u = new AppUser();
       em.persist(this.u);
       EditUserForm euf = new EditUserForm(u,true);
      
       euf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        euf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
               
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    list1.add(u); //Πρόσθεσε τον χρήστη στην λίστα
                    int row = list1.size() - 1;
        
                    usersTable.setRowSelectionInterval(row, row);
                    usersTable.scrollRectToVisible(usersTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                  
                }
                else{
                    thisFrame.setEnabled(true);//Εχει πατηθεί cancel άρα rollback
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = usersquery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //Διαγραφή χρήστη
        int s=usersTable.getSelectedRow();
        if (s>=0) {
           int answer = messageBox.YesNo("Είστε σίγουροι ότι θέλετε να προχωρήσετε στην διαγραφή");
            if (answer==0){//Ο χρήστης θέλει να διαγράψει την εγγραφή
               
            AppUser u = list1.get(usersTable.convertRowIndexToModel(s));
            if (u.equals(Session.loginUser)){ //Αν οχρήστης έχει κάνει login τοτε ΔΕΝ διαγράφεται
                 JOptionPane.showMessageDialog(null, "Δεν μπορείτε να διαγράψετε έναν συνδεδεμένο χρήστη","Προσοχή",JOptionPane.ERROR_MESSAGE);
            }
            else{
            list1.remove(u);
            em.remove(u);
            }
        }
        else {messageBox.infoBox("Δεν έχετε επιλέξει εγγραφή προς διαγραφή");}
            
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        //Επεξεργασία υπάρχοντος χρήστη
        s=usersTable.getSelectedRow();
        
        if (s>=0) {
            u = list1.get(usersTable.convertRowIndexToModel(s));
            EditUserForm euf = new EditUserForm(u,false);
            
            em.persist(u);
            
            euf.setVisible(true);
            thisFrame=this;
            thisFrame.setEnabled(false);
       
       
       //************
        euf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    list1.set(s,u); //Ενημέρωσε τον πίνακα
                    usersTable.setRowSelectionInterval(s, s);
                    usersTable.scrollRectToVisible(usersTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = usersquery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        }
         else {messageBox.infoBox("Δεν έχετε επιλέξει εγγραφή προς επεξεργασία");}
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // Ακυρο
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
         
        //Αποθηκευση στην βάση 24/2/2013
        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void usersTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_usersTableMouseReleased
        // TODO add your handling code here:
      
       
    }//GEN-LAST:event_usersTableMouseReleased
      
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListUsersForm().setVisible(true);
            }
        });
    }
   
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<AppUser> list1;
    private javax.swing.JTable usersTable;
    private javax.persistence.Query usersquery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    AppUser u;
    EntityManager em;
    JFrame thisFrame;
    int s; //Ποια γραμμή του πίνακα επιλέχθηκε
}
